﻿using ErrorOr;
using Gym.Application.Common.Interfaces;
using Gym.Domain.RoomAggregate;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gym.Application.Rooms.Queries.GetRoom
{
    public class GetRoomQueryHandler : IRequestHandler<GetRoomQuery, ErrorOr<Room>>
    {
        private readonly IGymsRepository _gymsRepository;
        private readonly IRoomsRepository _roomsRepository;

        public GetRoomQueryHandler(IGymsRepository gymsRepository, IRoomsRepository roomsRepository)
        {
            _gymsRepository = gymsRepository;
            _roomsRepository = roomsRepository;
        }

        public async Task<ErrorOr<Room>> Handle(GetRoomQuery request, CancellationToken cancellationToken)
        {
            var gym = await _gymsRepository.GetByIdAsync(request.GymId);

            if (gym is null)
            {
                return Error.NotFound(description: "没有找到该健身房信息");
            }

            if(!gym.HasRoom(request.RoomId))
            {
                return Error.NotFound(description: "没有找到该房间信息");
            }

            if (await _roomsRepository.GetByIdAsync(request.RoomId) is not Room room)
            {
                return Error.NotFound(description: "没有找到该房间信息");
            }

            return room;
        }
    }
}
